    //
    //  ViewController.swift
    //  suda
    //
    //  Created by youai on 2019/7/11.
    //  Copyright © 2019年 youi. All rights reserved.
    //
    
    import UIKit
    import MBProgressHUD
    import SwiftyUserDefaults
    
    class L_LoginVC: L_BaseViewController,UITextFieldDelegate {
        var imgLoad = UIImageView()
        
        let loginIdTextField = TextField()
        let passwdTextField = TextField()
        var loginBtn = Button()
        let rememberCheck = Button()
        var passwordImageView = UIImageView()
        var isfirst = true
        var isAutoLogin = false
        
        override func viewDidLoad() {
            let name1 = NSNotification.Name(rawValue:USER_TOKENTIMEOUT)
            NotificationCenter.default.addObserver(self, selector: #selector(notfifica(sender:)), name: name1, object: nil)
            
            if LocalStorage.getString(forKey: LOGIN_ID)?.count ?? 0 > 0,LocalStorage.getString(forKey: LOGIN_PASSWORD)?.count ?? 0 > 0 {
                imgLoad.isHidden = false
                loginAction()
            }
            else {
                imgLoad.isHidden = true
            }
        }
        
        ///只有在viewDidAppear才能取到非零的safeArea，但viewDidAppear会有延迟，
        ///只在应用第一个页面用viewDidAppear获取safeArea，其他页面会使用缓存
        override func viewDidAppear(_ animated: Bool) {
            super.viewDidAppear(animated)
            if isfirst {
                isfirst = false
                setupUI()
                
                print(self.getSafeArea())
                //            if (!(LocalStorage.getBool(forKey: YINSI_KEY) ?? false)) {
                //            }
            }
            else {
                passwdTextField.text = LocalStorage.getString(forKey: LOGIN_PASSWORD)
            }
            
            
        }
        
        //计算一次时间不用每次打开时间都获取
        func getTimeOutWithDate() -> Bool {
            let now = Date().timeIntervalSince1970
            if let lastTime = LocalStorage.getDouble(forKey: ZoneCodeTime),let timeNumber = anyToDouble(now-lastTime) {
                print(anyToString(timeNumber) ?? "null")
                let day = timeNumber/(3600*24)
                if day > 3.0 {
                    return true
                }
                else {
                    return false
                }
            }
            return true
        }
        
        //获取标识字常用典并存储
        func setZoneCode() {
            //        if !getTimeOutWithDate() {
            //            return
            //        }
            
            //        API.requestCode(pCode: ZoneCode103, callback: { (dic) in
            //            if let items = dic?.getDictList("items") {
            //                var ary = [Any]()
            //                for item in items {
            //                    ary.append(item)
            //                }
            //                LocalStorage.saveAry(ary, forKey: ZoneCode103)
            //            }
            //        })
            //
//            API.requestCode(pCode: ZoneCode104, callback: { (dic) in
//                if let items = dic?.getDictList("items") {
//                    var ary = [[String:Any?]]()
//                    for item in items {
//                        ary.append(item)
//                    }
//                    Defaults[\.ZoneCode104Key] = ary
//                }
//            })
            
            API.requestCode(pCode: ZoneCode105, callback: { (dic) in
                if let items = dic?.getDictList("items") {
                    var ary = [[String:Any?]]()
                    for item in items {
                        ary.append(item)
                    }
                    Defaults[\.ZoneCode105Key] = ary
                }
            })
            
            
            API.requestCode(pCode: ZoneCode106, callback: { (dic) in
                if let items = dic?.getDictList("items") {
                    var ary = [[String:Any?]]()
                    for item in items {
                        ary.append(item)
                    }
                    Defaults[\.ZoneCode106Key] = ary
                }
            })
            
            
            //        API.requestCode(pCode: ZoneCode107, callback: { (dic) in
            //            if let items = dic?.getDictList("items") {
            //                var ary = [Any]()
            //                for item in items {
            //                    ary.append(item)
            //                }
            //                LocalStorage.saveAry(ary, forKey: ZoneCode107)
            //            }
            //        })
            
            //        API.requestCode(pCode: ZoneCode110, callback: { (dic) in
            //            if let items = dic?.getDictList("items") {
            //                var ary = [Any]()
            //                for item in items {
            //                    ary.append(item)
            //                }
            //                LocalStorage.saveAry(ary, forKey: ZoneCode110)
            //            }
            //        })
            
            API.requestCode(pCode: ZoneCode117, callback: { (dic) in
                if let items = dic?.getDictList("items") {
                    var ary = [[String:Any?]]()
                    for item in items {
                        ary.append(item)
                    }
                    Defaults[\.ZoneCode117Key] = ary
                }
            })
            //        let now = Date().timeIntervalSince1970
            //        LocalStorage.saveDouble(anyToDouble(now), forKey: "ZoneCodeTime")
        }
        //中台信息同步
        func getUserInfoForBackstage(guid: String,token: String,mallId: String) {
            let params = ["guid": guid,
                          "token": token,
                          "mallId": mallId]
            API.formRequest(url: .YI_GetUserInfoForBackstage, params: params, callback: { r in
                if r.success {
                    print("中台信息同步成功...")
                }
            })
        }
        

        //
        func getSyssettingthird(callback: @escaping (Bool,[String:Any?]) -> Void) {
            API.formRequest(url: .YI_GetSyssettingthird, params: nil, callback: { (result) in
                if result.success {
                    if let dl = result.data?.getDictionary("data") {
                        callback(result.success, dl)
                    }
                    else {
                        callback(result.success, [:])
                    }
                }
            })
        }
    }
    
    
    // MARK:- 设置UI界面
    extension L_LoginVC {
        @objc override func setupUI() {
            super.setupUI()
            //登录控件区域
            let loginIdView = drawImgLineView(topOffset: 39,img: UIImage.init(named: "L_User"))
            //登录控件
            drawTextFieldInRoundCornerView(textField: loginIdTextField, placeHolder: "请输入手机号", roundCornerView: loginIdView.result)
            loginIdTextField.text = LocalStorage.getString(forKey: LOGIN_ID) //"s500cloud2@sd.com" 超级用户
            loginIdTextField.keyboardType = .phonePad
            loginIdTextField.delegate = self
            //            loginIdTextField.delegate = self
            loginIdTextField.addTarget(self, action: #selector(textfieldDidChanged(tf:)), for: UIControl.Event.editingChanged)
            
            let pasContainer = drawImgLineView(topOffset: 28,img: UIImage.init(named: "password_invisible"))
            //密码控件区域
            let passwdView = pasContainer.result
            passwordImageView = pasContainer.imageView
            //密码控件
            drawTextFieldInRoundCornerView(textField: passwdTextField, placeHolder: "请输入密码", roundCornerView: passwdView)
            passwdTextField.isSecureTextEntry = true
            passwdTextField.delegate = self
            passwdTextField.addTarget(self, action: #selector(psdfieldDidChanged(tf:)), for: UIControl.Event.editingChanged)
            passwdTextField.text = LocalStorage.getString(forKey: LOGIN_PASSWORD)
            passwdView.drawButton(title: "", titleColor: .clear, fontSize: 12) { (make) in
                make.left.equalToSuperview()
                make.centerY.equalToSuperview()
                make.height.width.equalTo(35)
            }.addTarget(self, action: #selector(pwdChangeCheckClicked(button:)), for: .touchUpInside)
            
            let btnunRemember = safeView.drawButton(title: "忘记密码", titleColor: .x333333, fontSize: 13) { (make) in
                make.top.equalTo(passwdView.snp.bottom).offset(30)
                make.left.equalToSuperview().offset(50)
            }
            btnunRemember.hitEdgInsets = .init(top: -20, left: -20, bottom: -20, right: -20)
            btnunRemember.addTarget(self, action: #selector(onRememberCheckClicked(button:)), for: .touchUpInside)
            
            let moreBtn = safeView.drawButton(title: "关于我们", titleColor: .x333333, fontSize: 13) { (make) in
                make.top.equalTo(passwdView.snp.bottom).offset(30)
                make.right.equalToSuperview().offset(-50)
            }
            moreBtn.hitEdgInsets = .init(top: -20, left: -20, bottom: -20, right: -20)
            moreBtn.addTarget(self, action: #selector(onMoerCheckClicked(button:)), for: .touchUpInside)
            
            //提交登录按钮
            loginBtn = drawRoundCornerButton(title:"登录", topOffset: 71)
            loginBtn.addTarget(self, action: #selector(onSubmitButtonClick(button:)), for: .touchUpInside)
            
            safeView.drawLabel(text: "首次登录前，请先激活账户", fontSize: 13, textColor: .x999999){ (make) in
                make.top.equalTo(passwdView.snp.bottom).offset(150)
                make.centerX.equalToSuperview()
            }
            
            let activateBtn = safeView.drawButton(title: "现在激活", titleColor: .x333333, fontSize: 13) { (make) in
                make.top.equalTo(passwdView.snp.bottom).offset(180)
                make.centerX.equalToSuperview()
            }
            activateBtn.hitEdgInsets = .init(top: -20, left: -20, bottom: -20, right: -20)
            activateBtn.addTarget(self, action: #selector(onActivateClicked(button:)), for: .touchUpInside)
            
            self.safeView.drawImage(imageView: imgLoad, named: "LaunchScreen") { (make) in
                make.top.left.right.bottom.equalToSuperview()
            }
            imgLoad.contentMode = .scaleAspectFit
            
            if loginIdTextField.text?.count ?? 0 > 0, passwdTextField.text?.count ?? 0 > 0 {
                loginBtn.isSelected = false
            }
            else {
                loginBtn.isSelected = true
            }
            
            initKeyboardObserver()
            fillAccessoryToolBar()
            if (!(LocalStorage.getBool(forKey: YINSI_KEY) ?? false)) {
                let popup = PopupConfirmImgBox(imgname: "yinsizhengce")
                popup.show(vc: self)
                popup.onSureButtonClick = {
                    LocalStorage.saveBool(true, forKey: YINSI_KEY)
                }
                popup.onTapImgClick = {
                    print("open img")
                    
                    let vc = M_SimpleArticleVC()
                    self.pushViewController(vc)
                    vc.headTitle.text = "隐私政策"
                    //                    vc.backButton.isHidden = true
                    vc.loadUrl("https://cw.51camel.com/appweb/agreement1.html")
                    //                    vc.backBtn.isHidden = false
                }
                popup.onCancelButtonClick = {
                    LocalStorage.saveBool(false, forKey: YINSI_KEY)
                    exit(0)
                }
            }
        }
        
    }
    
    
    // MARK:- 事件监听
    extension L_LoginVC {
        
        @objc func pwdChangeCheckClicked(button:UIButton){
            
            passwdTextField.isSecureTextEntry = !passwdTextField.isSecureTextEntry
            if passwdTextField.isSecureTextEntry {
                passwordImageView.image = UIImage(named: "password_invisible")
            } else {
                passwordImageView.image = UIImage(named: "password_visible")
            }
        }
        
        @objc func notfifica(sender:NSNotification) {
            popViewControllerToTop()
        }
        
        @objc func onRememberCheckClicked(button:UIButton){
            let vc = L_SMSCode_PasswordVC()
            pushViewController(vc)
        }
        
        @objc func onMoerCheckClicked(button:UIButton){
            let vc = L_AboutUsVC()
            pushViewController(vc)
        }
        
        @objc func onActivateClicked(button:UIButton){
            let vc = L_SMSCode_ActivateVC()
            pushViewController(vc)
        }
        
        func loginAction() {
            isAutoLogin = true
            let params :[String:Any] = ["loginName":LocalStorage.getString(forKey: LOGIN_ID)!,
                                        "password":LocalStorage.getString(forKey: LOGIN_PASSWORD)!,
                                        "serviceId":1,
                                        "verify":"0",
                                        "validate":"",
                                        "captchaId":""]
            MBProgressHUD.showOrIncrease()
            API.request(url: .L_Login, host:HOST_Login, params: params) { (result) in
                if result.success {
                    if let dl = result.data?.getDictionary("data") {
                        print(dl)
                        LocalStorage.saveString(self.loginIdTextField.text, forKey: LOGIN_ID)
                        LocalStorage.saveString(self.passwdTextField.text, forKey: LOGIN_PASSWORD)
                        LocalStorage.saveString(dl.getString("st") ?? "", forKey: LOGIN_ST)
                        
                        self.ProvisionalTicket(ticket: dl.getString("st") ?? "", guid: dl.getString("guid") ?? "")
                        
                    }
                }else{
                    self.imgLoad.isHidden = true
//                    let popup = PopupSureBox(title: result.errMsg ?? "账号或密码错误", sureText: "确定")
//                    popup.show(vc: UIViewController.topMostController() ?? self)
//                    popup.onSureButtonClick = {
//                        //确定执行
//                    }
                    MBProgressHUD.hideOrDecrease()
                }
            }
        }
        
        @objc func onSubmitButtonClick(button:UIButton){
            isAutoLogin = false
            
            if loginIdTextField.isEmpty(){
                let popup = PopupSureBox(title: "请输入手机号", infoText: "", sureText: "确定")
                imgLoad.isHidden = true
                popup.show(vc: UIViewController.topMostController() ?? self)
                popup.onSureButtonClick = {
                    //确定执行
                }
                
                return
            }
            else if !(loginIdTextField.text?.validateMobile() ?? false){
                let popup = PopupSureBox(title: "请填正确写登录手机号", infoText: "", sureText: "确定")
                imgLoad.isHidden = true
                popup.show(vc: UIViewController.topMostController() ?? self)
                popup.onSureButtonClick = {
                    //确定执行
                }
                
                return
            }else{
                LocalStorage.saveString(loginIdTextField.text, forKey: LOGIN_ID)
            }
            if passwdTextField.isEmpty(){
                let popup = PopupSureBox(title: "请填写登录密码", infoText: "", sureText: "确定")
                imgLoad.isHidden = true
                popup.show(vc: UIViewController.topMostController() ?? self)
                popup.onSureButtonClick = {
                    //确定执行
                }
                return
            }else if rememberCheck.isSelected {
                LocalStorage.saveString(passwdTextField.text, forKey: LOGIN_PASSWORD)
            }else {
//                LocalStorage.remove(forKey: LOGIN_PASSWORD)
            }
            
            let params :[String:Any] = ["loginName":loginIdTextField.text!,
                                        "password":passwdTextField.text!,
                                        "serviceId":1,
                                        "verify":"0",
                                        "validate":"",
                                        "captchaId":""]
            MBProgressHUD.showOrIncrease()
            API.request(url: .L_Login, host:HOST_Login, params: params) { (result) in
                if result.success {
                    if let dl = result.data?.getDictionary("data") {
                        print(dl)
                        LocalStorage.saveString(self.loginIdTextField.text, forKey: LOGIN_ID)
                        LocalStorage.saveString(self.passwdTextField.text, forKey: LOGIN_PASSWORD)
                        LocalStorage.saveString(dl.getString("st") ?? "", forKey: LOGIN_ST)
                        
                        self.ProvisionalTicket(ticket: dl.getString("st") ?? "", guid: dl.getString("guid") ?? "")
                        JPUSHService.setAlias(self.loginIdTextField.text!, completion: { (a, b, c) in
                            print("\(a) \(String(describing: b)) \(c)")
                        }, seq: 0)
                        
                        
                    }
                }else{
                    MBProgressHUD.hideOrDecrease()
                    self.imgLoad.isHidden = true
                    if result.errNo == 3004016 {
                        let vc = DefultVC()
                        self.pushViewController(vc)
                        return
                    }

                    let popup = PopupConfirmBox(info:result.errMsg ?? "登陆失败，帐号或密码错误", title: "")
                    popup.okBtn.setTitle("重新输入", for: .normal)
                    popup.show(vc: UIViewController.topMostController() ?? self)
                    popup.onSureButtonClick = {
                        self.passwdTextField.text = ""
                        self.passwdTextField.becomeFirstResponder()
                    }
                    
//                    let popup = PopupSureBox(title:result.errMsg ?? "登陆失败，帐号或密码错误", sureText: "确定")
//                    popup.show(vc: UIViewController.topMostController() ?? self)
//                    popup.onSureButtonClick = {
//                        //确定执行
//                    }
                }
            }
        }
        
        func ProvisionalTicket(ticket:String, guid:String) {
            let params :[String:Any] = ["provisionalTicket":ticket,
                                        "gid":guid]
            LocalStorage.saveString(guid, forKey: USER_GUID)
            API.request(url: .L_Ticket, params: params) { (result) in
                if let dl = result.data?.getDictionary("data") {
                    print(dl)
                    LocalStorage.saveString(dl.getString(USER_IDENTITYTOKEN), forKey: USER_IDENTITYTOKEN)
                    self.setZoneCode()
                    self.getMall()
                }else{
                    self.imgLoad.isHidden = true
                    MBProgressHUD.hideOrDecrease()
                    let popup = PopupSureBox(title:result.errMsg ?? "验票失败", sureText: "确定")
                    popup.show(vc: UIViewController.topMostController() ?? self)
                    popup.onSureButtonClick = {
                    }
                }
            }
        }
        
        //获取当前用户商城有则直接进入，没有跳到商城选择
        func getMall() {
            let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? ""]
            
            API.request(url: .S_GetMall, params: params) { (result) in
                MBProgressHUD.hideOrDecrease()
                if result.success,let dl = result.data?.getDictionary("data") {
                    LocalStorage.saveDic(dl, forKey: DEFULT_MALL)
                    LocalStorage.saveDic(dl, forKey: USER_DEFULT_MALL)
                    //                let vc = StoreListVC()
                    //                self.pushViewController(vc)
                    
                    self.getUserInfoForBackstage(guid: LocalStorage.getString(forKey: USER_GUID)!, token: LocalStorage.getString(forKey: USER_IDENTITYTOKEN)!, mallId: dl.getString("mallID") ?? "")
                    
                    MainTabBarController.getHomePageDynamic { (tabbarVC) in
                        if let vc = tabbarVC {
                            self.pushViewControllerWithAnimated(vc ,animated: !self.isAutoLogin)
                        }
                        self.imgLoad.isHidden = true
                    }
                    
                    
                }
                else {
                    let vc = StoreListVC(switchMallOnSelected: true)
                    self.pushViewControllerWithAnimated(vc ,animated: !self.isAutoLogin)
                    self.imgLoad.isHidden = true
                }
                self.getSyssettingthird(callback: { (sec,data) in
                    let qidianStr = data.getString("qidianJson")
                    if let qidiandic = qidianStr?.toJSONDictionary() {
                        LocalStorage.saveDic(qidiandic, forKey: QIDIAN_KEY)
                    }
                })
            }
        }
        
        @objc func  textfieldDidChanged(tf : UITextField) {
            if tf.text!.count > 11 {
                if let str = tf.text {
                    //截取前11个字符
                    let subStr = str.prefix(11)
                    tf.text = String(subStr)
                }
            }
            
            if loginIdTextField.text?.count ?? 0 > 0, passwdTextField.text?.count ?? 0 > 0 {
                loginBtn.isSelected = false
            }
            else {
                loginBtn.isSelected = true
            }
        }
        
        @objc func  psdfieldDidChanged(tf : UITextField) {
            if loginIdTextField.text?.count ?? 0 > 0, passwdTextField.text?.count ?? 0 > 0 {
                loginBtn.isSelected = false
            }
            else {
                loginBtn.isSelected = true
            }
        }
        
        //        func textViewDidChange(_ textView: UITextView) {
        //            if textView.text.count > 11 {
        //                if let str = textView.text {
        //                    //截取前11个字符
        //                    let subStr = str.prefix(11)
        //                    textView.text = String(subStr)
        //                }
        //            }
        //        }
    }
    
